package com.gitee.dufafei.spark.util

import java.security.SecureRandom

import javax.crypto.{Cipher, KeyGenerator}
import javax.crypto.spec.SecretKeySpec
import org.apache.commons.codec.binary.Base64

object EncryptUtil {

  // 密钥算法
  private val KEY_ALGORITHM  = "AES"
  // 加解密算法/工作模式/填充方式
  private val DEFAULT_CIPHER_ALGORITHM  = "AES/ECB/PKCS5Padding"
  private val SECRET_KEY_LENGTH = 128
  private val CHARSET = "UTF-8"
  private val Base64 = new Base64()

  /**
   * 字符串加密
   */
  def encrypt(data: String, password: String): String = {
    // 创建密码器
    val cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM)
    // 设置为加密模式
    cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password))
    val byteContent = data.getBytes(CHARSET)
    val encryptByte = cipher.doFinal(byteContent)
    Base64.encodeAsString(encryptByte)
  }

  /**
   * 字符串解密
   */
  def decrypt(base64Data: String, password: String): String = {
    val cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM)
    // 设置为解密模式
    cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password))
    val result = cipher.doFinal(Base64.decode(base64Data))
    new String(result, CHARSET)
  }

  private def getSecretKey(password: String): SecretKeySpec = {
    val keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM)
    keyGenerator.init(SECRET_KEY_LENGTH, new SecureRandom(password.getBytes()))
    val secretKey = keyGenerator.generateKey()
    new SecretKeySpec(secretKey.getEncoded, KEY_ALGORITHM)
  }
}
